package com.quantstack.llhttplibrary;

import android.util.Log;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/2/9 10:28
 * @Notes 向请求头里添加公共参数
 */
public class HttpCommonInterceptor implements Interceptor {
    //请求头
    private Map<String,String> mHeaderParamsMap = new HashMap<>();
    //公共get参数
    private Map<String,String> mGetParamsMap = new HashMap<>();
    //公共post参数
    private Map<String,String> mPostParamsMap = new HashMap<>();

    public HttpCommonInterceptor() {
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Log.d("HttpCommonInterceptor","add common params");
        //获取到方法
        Request oldRequest = chain.request();
        String method = oldRequest.method();
        // 新的请求
        Request.Builder requestBuilder =  oldRequest.newBuilder();
        requestBuilder.method(oldRequest.method(),
                oldRequest.body());

        //添加公共参数,添加到header中
        if(mHeaderParamsMap!=null&&mHeaderParamsMap.size() > 0){
            for(Map.Entry<String,String> params:mHeaderParamsMap.entrySet()){
                requestBuilder.header(params.getKey(),params.getValue());
            }
        }

        //添加参数到url
        if(mGetParamsMap!=null&&mGetParamsMap.size()>0){
            HttpUrl.Builder builder = oldRequest.url().newBuilder();
            for(Map.Entry<String,String> params:mGetParamsMap.entrySet()){
                builder.addEncodedQueryParameter(params.getKey(),params.getValue());
            }
            HttpUrl httpUrl = builder.build();
            // 将最终的url填充到request中
            requestBuilder.url(httpUrl);
        }
        Request newRequest = requestBuilder.build();
        return chain.proceed(newRequest);
    }

    public static class Builder{
        HttpCommonInterceptor mHttpCommonInterceptor;
        public Builder(){
            mHttpCommonInterceptor = new HttpCommonInterceptor();
        }
        public Builder addHeaderParams(String key, Object value){
            mHttpCommonInterceptor.mHeaderParamsMap.put(key,String.valueOf(value));
            return this;
        }
        public Builder addGetParams(String key, Object value){
            mHttpCommonInterceptor.mGetParamsMap.put(key,String.valueOf(value));
            return this;
        }
        public Builder addPostParams(String key, Object value){
            mHttpCommonInterceptor.mPostParamsMap.put(key,String.valueOf(value));
            return this;
        }
        public HttpCommonInterceptor build(){
            return mHttpCommonInterceptor;
        }
    }
}
